/*
 * POP3.fx
 *
 * Created on 10.02.2010, 23:27:29
 */

package crudfx.data;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
 * @author 1024
 */

public class POP3 extends DataTree{
    public var host:String="";
    public var login:String="";
    public var password:String="";
    public var port:Integer=110;
    init{
        fill();
        }
    function fill():Void{
        try{
            var props:Properties=java.lang.System.getProperties();
            props.setProperty("mail.pop3.socketFactory.class","javax.net.ssl.SSLSocketFactory");
            props.put("mail.pop3.host",host);
            props.put("mail.pop3.port",port);
            props.put("mail.pop3.starttls.enable","true");
            //props.put("mail.pop3.rsetbeforequit", "true");
            //props.put("mail.pop3s.rsetbeforequit", "true");
            props.setProperty("mail.pop3.socketFactory.fallback","false");
            var session:Session=Session.getInstance(props, null);
            var store:Store=session.getStore("pop3");
            store.connect(login, password);
            var folder:Folder=store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            //System.out.println("Messages total: " + folder.getNewMessageCount() + "/" + folder.getMessageCount());
            var msgs:Message[]=folder.getMessages();
            var fp:FetchProfile=new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);
            var addresses:Address[];
            var address:Address[];
            for(m in msgs){
                var message:DataTree=DataTree{
                    name:"message"
                    };
                insert message into children;
                addresses=m.getFrom();
                if(sizeof addresses>0){
                    for(a:Address in addresses){
                        var t:DataTree=DataTree{
                            name:"address"
                            };
                        t.asString("").value=a.toString();
                        insert t into message.node("from").children;
                        }
                    }
                message.node("subject").asString("").value=m.getSubject();
                var d:Date=m.getSentDate();
                if(d==null)d=new Date();
                message.node("sent").asNumber(0).value=d.getTime();
                addPart(m,message.node("parts"));
                //m.setFlag(Flags.Flag.DELETED,false);
                }
            folder.close(false);
            store.close();
        }catch(x){
            x.printStackTrace();
            }
        }
    function addPart(m:Part,base:DataTree):Void{
        var part:DataTree=DataTree{name:"part"};
        var ct:String=m.getContentType();
        try{
            part.node("content-type").asString("").value=(new ContentType(ct)).toString();
        }catch(x){
            x.printStackTrace();
            part.node("content-type").asString("").value=ct;
            }
	if(m.getFileName()!=null)part.node("file").asString("").value=m.getFileName();
        if(m.isMimeType("text/plain")){
            part.node("MIME").asString("").value="text/plain";
            part.node("content").asString("").value=m.getContent().toString();
            }
        else{
            if(m.isMimeType("multipart/*")){
                part.node("MIME").asString("").value="multipart/*";
                var multipart:Multipart=m.getContent() as Multipart;
                var nn:Integer=multipart.getCount();
                while(nn>0){
                    nn--;
                    var bodyPart:BodyPart=multipart.getBodyPart(nn);
                    addPart(bodyPart,part.node("parts"));
                    }
                }
            else{
                if(m.isMimeType("message/rfc822")){
                    part.node("MIME").asString("").value="message/rfc822";
                    addPart((m.getContent() as Part),part.node("parts"));
                    }
                else{
                    var o:Object=m.getContent();
                    if(o instanceof String){
                        part.node("MIME").asString("").value="unknown string";
                        part.node("content").asString("").value=o.toString();
                        }
                    else{
                        if(o instanceof InputStream){
                            part.node("MIME").asString("").value="unknown binary";
                            var is:InputStream=o as InputStream;
                            var c:Integer;
                            var sb:java.lang.StringBuffer=new java.lang.StringBuffer();
                            while ((c = is.read()) != -1){
                                sb.append("/");
                                sb.append(c);
                                }
                            part.node("content").asString("").value=sb.toString();
                            }
                        else{
                            part.node("MIME").asString("").value="unknown";
                            part.node("content").asString("").value="{o}";
                            }
                        }
                    }
                }
            }
        //
        insert part into base.children;
        }
    }
